<template>
  <view class="page-container">
    <GlobalTopBar ref="topBarRef" class="topbars"> </GlobalTopBar>

    <view class="page_content">
      <DragButton>
        <button
          class="flex_center tdkf contactBtn"
          open-type="contact"
          bindcontact="onContact"
        >
          <image
            class="kefu2_img"
            :src="`${store.imgDomain}kfbtn1.jpg`"
            mode="scaleToFill"
          />
        </button>
      </DragButton>

      <image
        class="page_image"
        :src="`${store.imgDomain}home_1.png`"
        mode="scaleToFill"
      />
      <view class="centers">
        <!-- 顶部图标文字 -->
        <image
          class="home2img"
          :src="`${store.imgDomain}home_2.png`"
          mode="scaleToFill"
        />

        <!-- 搜索 -->
        <view class="sousuobox">
          <view class="sounpx">
            <view class="left flex" style="width: 100%">
              <view @click="store.to('/pages/public/addressqh')">{{
                store.cityInfo.areaname || '金华市'
              }}</view>
              <uni-icons
                @click="store.to('/pages/public/addressqh')"
                type="down"
                size="12"
                color="#999"
              ></uni-icons>
              <view class="line"></view>
              <view
                class="flex"
                @click="store.to('/pages/server/sousuo')"
                style="flex: 1"
              >
                <uni-icons type="search" size="20" color="#999"></uni-icons>
                <view class="t2">请输入关键字</view>
              </view>
              <view class="btn">搜索</view>
            </view>
          </view>
        </view>

        <!-- 金刚区 -->
        <view class="JBS">
          <swiper
            class="swiper"
            indicator-dots
            indicator-color="#B2D0F4"
            indicator-active-color="#0791E7"
          >
            <!-- 轮播项1 -->
            <swiper-item v-for="(item, index) in homeflList" :key="index + 1">
              <view class="ul">
                <view
                  class="li"
                  :class="{ ac: y < 5 && index === 0 }"
                  v-for="(i, y) in item"
                  :key="y + 1"
                  @click="jgFun(i)"
                >
                  <image v-if="i?.icon" :src="i.icon" mode="aspectFill" />
                  <text>{{ i.goods_category_title }}</text>
                </view>
              </view>
            </swiper-item>
          </swiper>
          <!-- 政策服務 -->
          <view class="zcorfw">
            <image
              @click="
                store.to(
                  '/pages/public/agreement?url=wxapp/index/getVipPolicyIntrodction',
                )
              "
              :src="`${store.imgDomain}home_3.jpg`"
              mode="scaleToFill"
            />
            <image
              @click="
                store.to(
                  '/pages/public/agreement?url=wxapp/index/getServicePriceDisclosure',
                )
              "
              :src="`${store.imgDomain}home_4.jpg`"
              mode="scaleToFill"
            />
          </view>
          <view
            class="home_7"
            @click="
              uni.redirectTo({
                url: '/pages/services/index',
              })
            "
          >
            <image
              :src="`${store.imgDomain}home_9.jpg`"
              alt=""
              mode="widthFix"
            />
          </view>
        </view>
        <!-- 推荐 -->
        <view class="ultabs">
          <view
            class="lit"
            :class="{ ac: indexs === index }"
            v-for="(item, index) in categoryList"
            :key="index + 1"
            @click="indexs = index"
          >
            <view class="lit_text">{{ item.goods_category_title }}</view>
          </view>
        </view>
        <!-- 内容 -->
        <!-- refresher-enabled
          :refresher-triggered="isRefreshing"
          @refresherrefresh="handleRefresh"
          @scrolltolower="handleLoadMore" -->
        <scroll-view
          class="scroll-Y"
          scroll-y
          refresher-background="#f5f5f5"
          refresher-threshold="80"
        >
          <view class="ulList">
            <template v-for="(item, index) in goods_list" :key="index + 1">
              <view
                v-if="index < 4"
                class="li"
                @click="
                  store.to(`/pages/server/serverDetails?id=${item.id}&type=1`)
                "
              >
                <image :src="item.thumbnail" mode="aspectFill" />
                <view class="texts">
                  <view class="t1">{{ item.goods_title }}</view>
                  <view class="t2"
                    >￥<text style="font-weight: 700; font-size: 30rpx">{{
                      item.buy_price
                    }}</text
                    >起</view
                  >
                  <view
                    class="lcoupon"
                    v-if="item.goods_relation_coupon_list.length"
                    >领券<uni-icons
                      type="right"
                      size="14"
                      color="#fff"
                    ></uni-icons
                  ></view>
                </view>
              </view>
            </template>
          </view>
          <view class="flex_center wfw_box" v-if="!goods_list.length">
            <image
              class="wfw_img"
              :src="`${store.imgDomain}home_6.png`"
              mode="widthFix"
            />
            <text>暂无服务</text>
          </view>
        </scroll-view>
        <!-- 介绍流程 -->
        <image
          class="lcimg"
          :src="`${store.imgDomain}home_8.jpg`"
          mode="widthFix"
        />
      </view>

      <!-- 底部菜单 -->
      <tabBar :current-index="0" :tab-list="store.tabList"></tabBar>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive, watch, onMounted } from 'vue';
import { useCounterStore } from '@/store';
import { onLoad, onShow } from '@dcloudio/uni-app';
import tabBar from '@/components/tabBar.vue';
import request from '@/utils/request';
import Drawer from '@/components/Drawer.vue';
import { validatePhone } from '@/utils/validate';
import DragButton from '@/components/dragon-dragButton/index.vue';

// 控制抽屉显示状态
const topBarRef = ref();
const showDrawer = ref(false);
const showBottomDrawer = ref(false);
const store = useCounterStore();
const homeflList = ref([]);
const indexs = ref(0);

const categoryList = ref([]);
const goods_list = ref([]);
const isRefreshing = ref(false); // 下拉刷新状态
const isLoading = ref(false); // 加载更多状态
const isNext = ref(true);
const pageNum = ref(1);
const pageSize = ref(10);

const handleContact = (e) => {
  console.log(e);
};

// 自定义样式（可选）
// const tabStyle = {
//   bgColor: '#fafafa',
//   activeColor: '#ff6700',
//   borderColor: '#f0f0f0',
// };
// 获取首页服务分类
const getGoodsCategoryForWxAppIndex = async () => {
  const data = await request('wxapp/index/getGoodsCategoryForWxAppIndex');
  homeflList.value = splitArray(data, 20);
};
const splitArray = (arr, size) => {
  // 处理空数组或无效size
  if (!arr.length || size <= 0) return [];

  const result = [];
  // 循环拆分：每次取size个元素组成子数组
  for (let i = 0; i < arr.length; i += size) {
    // 从索引i开始，截取size个元素
    const chunk = arr.slice(i, i + size);
    result.push(chunk);
  }
  return result;
};

// 获取首页推荐服务所需一级分类
const getAllFirstGoodsCategoryList = async () => {
  categoryList.value = await request(
    'wxapp/index/getAllFirstGoodsCategoryList',
  );
  pageNum.value = 1;
  getGoodsListByGoodsCategoryId(true);
};
// 给定分类Id获取服务项目列表数据（分页）
const getGoodsListByGoodsCategoryId = async (isRefresh = false) => {
  try {
    const data = await request('wxapp/index/getGoodsListByGoodsCategoryId', {
      goods_category_id: categoryList.value[indexs.value].id,
      currpage: pageNum.value,
      pagesize: pageSize.value,
    });
    isNext.value = data.page.isNext;
    if (isRefresh) {
      goods_list.value = [...data.list].slice(0, 4);
    } else {
      goods_list.value = [...goods_list.value, ...data.list].slice(0, 4);
    }
  } finally {
    isRefreshing.value = false;
    isLoading.value = false;
  }
};
// 下拉刷新处理
const handleRefresh = () => {
  // 重置状态
  pageNum.value = 1;
  isRefreshing.value = true;
  // 重新加载数据
  getGoodsListByGoodsCategoryId(true);
};
// 触底加载更多处理
const handleLoadMore = () => {
  if (!isNext.value || isLoading.value) return;
  // 加载下一页
  pageNum.value++;
  isLoading.value = true;
  getGoodsListByGoodsCategoryId();
};

watch(
  () => indexs.value,
  (val) => {
    getGoodsListByGoodsCategoryId(true);
  },
);

const jgFun = async (item) => {
  if (item.goods_category_level === 3) {
    try {
      const data = await request(
        'wxapp/index/getGoodsInfoAndRelationGoodsByGoodsCategoryId',
        { goods_category_id: item.id },
      );
      if (data.length) {
        store.to(`/pages/server/serverDetails?id=${item.id}&type=2`);
      } else {
        uni.showToast({
          title: '暂无相关服务，请联系客服',
          icon: 'none',
        });
      }
    } catch {
      uni.showToast({
        title: '暂无相关服务，请联系客服',
        icon: 'none',
      });
    }
  } else {
    store.options = { ...item };
    uni.redirectTo({
      url: '/pages/services/index',
    });
  }
};

// 解析 query 字符串为对象
function parseQueryString(queryStr) {
  const obj = {};
  if (!queryStr) return obj;
  const pairs = queryStr.split('&');
  pairs.forEach((pair) => {
    const [key, value] = pair.split('=');
    if (key) {
      obj[key] = decodeURIComponent(value || ''); // 解码值（避免中文乱码）
    }
  });
  return obj;
}

// 【腾讯地图】经纬度获取地信息
const getTencentMapAddress = async (latitude, longitude, name) => {
  const data = await request('wxapp/common/getTencentMapAddress', {
    location: `${latitude},${longitude}`,
  });
  store.cityInfo.areaname = data.ad_info.city;
};

onLoad((option) => {
  // 获取用户当前位置
  uni.getLocation({
    type: 'gcj02', // 坐标系类型：gcj02（国测局坐标，微信小程序等常用）、wgs84（GPS坐标）、bd09ll（百度坐标）
    altitude: false, // 是否获取高度信息（默认false）
    isHighAccuracy: false, // 是否开启高精度定位（部分平台支持，可能影响性能）
    success: (res) => {
      getTencentMapAddress(res.latitude, res.longitude);
    },
    fail: (err) => {
      console.log('定位失败', err);
      // 常见失败原因：用户拒绝授权、设备定位未开启、网络问题等
    },
    complete: () => {
      // 无论成功失败都会执行
    },
  });

  if (option.q) {
    console.log('携带的数据11=>', option.q);
    // 1. 获取 q 参数（注意：需要 decodeURIComponent 解码，因为 URL 可能被编码）
    const q = decodeURIComponent(option.q);
    console.log('携带的数据解码=>', q);
    const queryStr = q.split('?')[1]; // 获取 "id=123&type=2"
    const params = parseQueryString(queryStr);
    console.log('params:', params);
  }
});
onShow(() => {
  if (!store.open_id || !store.is_type) {
    uni.reLaunch({
      url: '/pages/login/index',
    });
  } else if (store.is_type === 1) {
    getGoodsCategoryForWxAppIndex();
    getAllFirstGoodsCategoryList();
  }
});
</script>

<style scoped lang="scss">
.page-container {
  position: relative;
  .page_image {
    position: absolute;
    top: 0;
    left: 0;
    width: 750rpx;
    height: 443rpx;
    z-index: 0;
  }
  .centers {
    box-sizing: border-box;
    position: relative;
    z-index: 1;

    .home2img {
      display: block;
      margin: 0 auto;
      width: 605rpx;
      height: 221rpx;
      transform: translateY(-50rpx);
    }
    .sousuobox {
      margin-top: -80rpx;
      height: max-content;
      box-sizing: border-box;
      padding: 12rpx;
    }
    .sounpx {
      position: relative;
      z-index: 2;

      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      padding: 12rpx 12rpx 12rpx 20rpx;
      border-radius: 37rpx;
      background-color: #fff;
      .left {
        display: flex;
        align-items: center;

        view {
          flex-shrink: 0;
          font-size: 24rpx;
        }
        .line {
          width: 1rpx;
          height: 38rpx;
          margin: 0 20rpx;
          background-color: $uni-text-color-grey;
        }
        .t2 {
          margin-left: 5rpx;
          color: $uni-text-color-grey;
        }
      }
      .btn {
        padding: 0 33rpx;
        background-color: #0086f2;
        line-height: 51rpx;
        border-radius: 25rpx;
        color: #fff;
        font-size: 24rpx;
      }
    }
    .ul {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
      gap: 10rpx;
      place-content: center;
      box-sizing: border-box;
      padding: 40rpx 30rpx 54rpx;
      .li {
        height: 120rpx;
        font-size: 24rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        &.ac {
          height: 150rpx;
          font-size: 26rpx;
          .text {
          }
          image {
            width: 108rpx;
            height: 108rpx;
            margin-bottom: 20rpx;
          }
        }
        image {
          width: 70rpx;
          height: 70rpx;
          margin-bottom: 10rpx;
          border-radius: 34rpx;
        }
      }
    }
  }
  .zcorfw {
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 33rpx;
    margin-bottom: 30rpx;
    image {
      width: 330rpx;
      height: 306rpx;
      border-radius: 10rpx;
    }
  }
}
.ultabs {
  margin-top: 20rpx;
  box-sizing: border-box;
  padding: 0 33rpx;
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  .lit {
    width: 17%;
    font-size: 28rpx;
    position: relative;
    flex-shrink: 0;
    padding: 0 15rpx 30rpx;
    .lit_text {
      text-align: center;
      width: 100%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    &.ac {
      color: #4097f3;
      &::after {
        content: ' ';
        position: absolute;
        bottom: 15rpx;
        left: 50%;
        transform: translate(-50%);
        width: 50%;
        height: 6rpx;
        border-radius: 3rpx;
        background-color: #4097f3;
      }
    }
  }
}
.ulList {
  position: relative;
  box-sizing: border-box;
  padding: 0 33rpx;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  background-color: #eaf2fc;
  .li {
    width: 48.5%;
    background-color: #fff;
    margin-bottom: 20rpx;
    border-radius: 20rpx;
    overflow: hidden;
    image {
      width: 100%;
      height: 247rpx;
    }
    .texts {
      position: relative;
      box-sizing: border-box;
      padding: 20rpx;
    }
    .t1 {
      margin-bottom: 10rpx;
      font-weight: 700;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .t2 {
      font-size: 24rpx;
      margin-bottom: 10rpx;
      color: #ff0000;
      text {
        font-size: 30rpx;
      }
    }
  }
}
.lcimg {
  width: 750rpx;
}
.JBS {
  border-radius: 25rpx 25rpx 0 0;
  overflow: hidden;
  margin-top: 20rpx;
  background: linear-gradient(to bottom, #fff, 80%, #eaf2fc);
}
.swiper {
  height: 650rpx;
}
.page_content {
  background-color: #eaf2fc;
  padding-bottom: 120rpx;
}
.wfw_box {
  flex-direction: column;
  margin-bottom: 30rpx;
  text {
    color: $uni-text-color-grey;
  }
}
.wfw_img {
  margin-bottom: 20rpx;
  width: 200rpx;
}
.scroll-Y {
  margin-top: 20rpx;
  height: 830rpx;
}
.wfw_box {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.lcoupon {
  position: absolute;
  top: 65.5%;
  right: 20rpx;
  transform: translateY(-50%);
  font-size: 24rpx;
  color: #fff;
  display: flex;
  align-items: center;
  padding: 5rpx 10rpx;
  background-color: #fe0f10;
  border-radius: 10rpx;
}

.kefu2_img {
  width: 125rpx;
  height: 125rpx;
}
.tdkf {
  border-radius: 50%;
  image {
    border-radius: 50%;
  }
  &::after {
    display: none;
  }
}
.home_7 {
  box-sizing: border-box;
  padding: 0 33rpx;

  image {
    border-radius: 20rpx;
    width: 100%;
  }
}
</style>
